package com.atguigu.srb.sms.controller.api;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.atguigu.common.exception.Assert;
import com.atguigu.common.result.R;
import com.atguigu.common.result.ResponseEnum;
import com.atguigu.common.util.RandomUtils;
import com.atguigu.common.util.RegexValidateUtils;
import com.atguigu.srb.sms.client.CoreUserinfoClient;
import com.atguigu.srb.sms.service.SmsService;
import com.atguigu.srb.sms.util.SmsProperties;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * @Author: Bright
 * @Date: 2022-04-15 15:39
 * @Description: com.atguigu.srb.sms.controller.api
 * @version: 1.0
 */
@Api(tags = "sms服务")
@RestController
@RequestMapping("/api/sms")
@Slf4j
public class ApiSmsController {
    @Resource
    private SmsService smsService;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private CoreUserinfoClient coreUserinfoClient;

    @ApiOperation("发送短信")
    @GetMapping("/send/{mobile}")
    public R send(
            @ApiParam(value = "手机号", required = true)
            @PathVariable String mobile) {
        //判断手机号是否为空
        Assert.notNull(mobile, ResponseEnum.MOBILE_NULL_ERROR);

        //判断手机号格式是否正确
        Assert.isTrue(RegexValidateUtils.checkCellphone(mobile), ResponseEnum.MOBILE_ERROR);
        boolean result = coreUserinfoClient.checkMobile(mobile);
        log.info("手机注册返回值:"+result);
        Assert.isTrue(!result, ResponseEnum.MOBILE_EXIST_ERROR);


        HashMap<String, Object> map = new HashMap<>();
        String code = RandomUtils.getFourBitRandom();
        log.info("验证码:" + code);
        map.put("code", code);
        //向redis中存入code
        redisTemplate.opsForValue().set("srb:sms:code" + mobile, code, 5, TimeUnit.MINUTES);
        log.info("向redis中存入code");

        smsService.send(mobile, SmsProperties.TEMPLATE_CODE, map);

        return R.ok().message("发送成功");
    }

}
